<!-- eslint-disable vue/require-valid-default-prop -->
<script setup>
import {  watchEffect } from 'vue'
import { reactive } from 'vue'
import { addRole,updateRole } from '@/api'
import { message } from 'ant-design-vue'
// 使用defineProps方法来接收props
const props = defineProps({
    showDialog: {
        type: Boolean,
        default: false
    },
    roleData: {  
        type: Object,  
        default: () => null  
    },
    title:{
        type:String,
        default:false
    }  
})
const formData = reactive({  
    name: '',  
    state: 0,  
    description: ''  
});  
  // 2.执行函数 return 计算之后的值 变量接受
  watchEffect(() => {  
    if (props.roleData) {  
        Object.assign(formData, props.roleData); 
    } else {  
        formData.name = '';  
        formData.state = 0;  
        formData.description = '';  
    }  
}); 

const emit = defineEmits(["update:showDialog", "addSuccess"])
const close = () => {
    // 子传父
    emit("update:showDialog", false)
}
const onFinished = async(values) => {
    if (props.roleData) {  
       // 编辑角色的逻辑  
       try {  
            await updateRole({ ...values, id: props.roleData.id }); // 传递角色 ID  
            message.success("编辑成功");  
        } catch (error) {  
            message.error("编辑失败");  
        }  
    } else {  
        await addRole(values);  
        message.success("新增成功");  
    }  
    close(); // 关闭弹层  
    emit("addSuccess");  
    formData.name = ""
    formData.state = 0
    formData.description = ""

}
defineExpose({
    formData
 })
</script>
<template>
<a-modal :footer="null" :visible="props.showDialog" @cancel="close" :title="props.title">
        <a-form @finish="onFinished" :model="formData" :label-col="{ span: 4 }">
            <a-form-item name="name" label="角色名称" :rules="[{ required: true, message: '角色名称不能为空', trigger: 'blur' }]">
                <a-input v-model:value="formData.name" placeholder="请输入角色名称"></a-input>
            </a-form-item>
            <a-form-item name="state" label="启用">
                <a-switch :checkedValue="1" :unCheckedValue="0" v-model:checked="formData.state"></a-switch>
            </a-form-item>
            <a-form-item name="description" label="角色描述" :rules="[{ required: true, message: '角色描述不能为空', trigger: 'blur' }]">
                <a-textarea v-model:value="formData.description" placeholder="请输入角色描述"></a-textarea>
            </a-form-item>
            <a-form-item>
                <a-row type="flex" justify="center">
                    <a-space>
                    <a-button type="primary" html-type="submit">确定</a-button>
                   <a-button @click="close">取消</a-button>
                  </a-space>
                </a-row>
            </a-form-item>
        </a-form>
    </a-modal>
</template>